package com.cloudbroker.bcs.platform.ltb.middle.aspect;

import com.cloudbroker.bcs.common.annotation.CreditsOper;
import com.cloudbroker.bcs.common.annotation.NoLogin;
import com.cloudbroker.bcs.common.constants.type.BusinessType;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.csvc.credits.api.vo.request.CreditsOperForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.ask.vo.AskAddForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.base.vo.HSLTBBaseVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.comment.vo.CommentAddForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.comment.vo.CommentTopForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.CombEntrustTransForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.CombSubscribeTransForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.CombineFocusForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.FocusInterestByTransForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.back.UserLoginBack;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.viewpoint.vo.ViewpointShareForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.viewpoint.vo.ViewpointUpvoteForm;
import com.cloudbroker.bcs.platform.ltb.middle.entity.CommentMsg;
import com.cloudbroker.bcs.platform.ltb.middle.entity.credits.*;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.credits.CreditsExtService;
import com.cloudbroker.bcs.platform.ltb.middle.model.UserCache;
import com.cloudbroker.bcs.platform.ltb.middle.service.*;
import com.cloudbroker.bcs.platform.ltb.middle.util.CreditsCacheUtil;
import com.cloudbroker.bcs.platform.ltb.middle.util.UserTokenUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lili19289 on 2016/11/10.
 */
public class CreditsAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(CreditsAspect.class);

    @Resource
    private CreditsRuleService creditsRuleService;
    @Resource
    private TaskConfigureService taskConfigureService;
    @Resource
    private TaskProgressService taskProgressService;
    @Resource
    private CreditsLimitService creditsLimitService;
    @Resource
    private CreditsLogService creditsLogService;
    @Resource
    private CreditsExtService creditsService;

    @Resource
    private CommentService commentService;

    public void creditsOpera(JoinPoint pjp,Object retValue) throws Throwable {
        // 在Spring的环境里，signature就是MethodSignature
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 获取Method
        Method method = methodSignature.getMethod();
        if(!method.isAnnotationPresent(CreditsOper.class)) {
            return ;
        }
       try{
            operCredits(pjp,method,retValue);
       }catch (Exception e){
           LOGGER.error("积分操作错误--------",e);
           //这里要添加补偿操作
       }finally {
           return ;
       }

    }


    public void operCredits(JoinPoint pjp,Method method,Object retValue)throws Throwable{
        //获取操作信息
        CreditsOper creditsOper = method.getAnnotation(CreditsOper.class);
        BusinessType type = creditsOper.type();
        int business_type = type.toInt();
        int direction = creditsOper.direction();
        int multiply=1;//任务完成情况 判断是否加倍
        UserCache userCache = null;
        String access_token="";
        //获取用户信息
        HSLTBBaseVO param=null;
        //登录接口处理
        HSBCPSBackVO backVO = (HSBCPSBackVO)retValue;
        if(backVO!=null &&  !"0".equals(backVO.getError_no())){
            return ;
        }
        if(method.isAnnotationPresent(NoLogin.class)){
            UserLoginBack loginBack = (UserLoginBack)retValue;
            access_token = loginBack.getUser_token();
        }else{
            for(Object arg : pjp.getArgs()){
                if(arg instanceof HSLTBBaseVO){
                    param = (HSLTBBaseVO)arg;
                    access_token = param.getUser_token();
                    break;
                }
            }

        }
        userCache = UserTokenUtil.queryUserToken(access_token);
        String company_id=userCache.getBrokerVO().getCompany_id();
        //目前只对国联开放积分功能
        if(!"20034".equals(company_id)){
            return;
        }
        Long user_id = userCache.getBrokerVO().getUser().getUser_id();
        String operId=null;
        try{
            switch (business_type){
                case 10001://每日打开APP
                    if(CreditsCacheUtil.isLoginded(user_id)){
                        return ;
                    }
                    CreditsCacheUtil.addLoginTime(user_id);
                    break;
                case 10002://观点点赞
                    ViewpointUpvoteForm viewpointUpvoteForm=(ViewpointUpvoteForm)param;
                    operId = viewpointUpvoteForm.getViewpoint_id();
                    if(CreditsCacheUtil.isExitCreditsOper(user_id,business_type,operId)){//检查是否操作过积分
                        return ;
                    }
                    CreditsCacheUtil.addCreditOper(user_id,business_type,operId);
                    break;
                case 10003://观点分享
                    ViewpointShareForm viewpointShareForm = (ViewpointShareForm)param;
                    operId = viewpointShareForm.getViewpoint_id();
                    if(CreditsCacheUtil.isExitCreditsOper(user_id,business_type,operId)){//检查是否操作过积分
                        return ;
                    }
                    CreditsCacheUtil.addCreditOper(user_id,business_type,operId);
                    break;
                case 10004://评论
                    CommentAddForm commentAddForm =(CommentAddForm)param;
                    operId = commentAddForm.getComment_target_id()+commentAddForm.getComment_type();
                    if(CreditsCacheUtil.isExitCreditsOper(user_id,business_type,operId)){//检查是否操作过积分
                        return ;
                    }
                    CreditsCacheUtil.addCreditOper(user_id,business_type,operId);
                    break;
                case 10005://评论置顶
                    CommentTopForm commentTopForm = (CommentTopForm)param;
                    operId = commentTopForm.getComment_id();
                    CommentMsg comment = commentService.get(operId);
                    user_id=comment.getUser_id();
                    company_id=comment.getCompany_id();
                    if(CreditsCacheUtil.isExitCreditsOper(user_id,business_type,operId)){//检查是否操作过积分
                        return ;
                    }
                    CreditsCacheUtil.addCreditOper(user_id,business_type,operId);
                    break;
                case 10006://关注投顾
                    FocusInterestByTransForm focusInterestByForm = (FocusInterestByTransForm)param;
                    operId = focusInterestByForm.getAdviser_id();
                    if(CreditsCacheUtil.isExitCreditsOper(user_id,business_type,operId)){//检查是否操作过积分
                        return ;
                    }
                    CreditsCacheUtil.addCreditOper(user_id,business_type,operId);
                    break;
                case 10007://关注组合
                    CombineFocusForm combineFocusForm =(CombineFocusForm)param;
                    operId = combineFocusForm.getCombi_code();
                    if(CreditsCacheUtil.isExitCreditsOper(user_id,business_type,operId)){//检查是否操作过积分
                        return;
                    }
                    CreditsCacheUtil.addCreditOper(user_id,business_type,operId);
                    break;
                case 10008://订阅
                    CombSubscribeTransForm combSubscribeForm =(CombSubscribeTransForm)param;
                    operId = combSubscribeForm.getCombi_code();
                    if(CreditsCacheUtil.isExitCreditsOper(user_id,business_type,operId)){//检查是否操作过积分
                        return;
                    }
                    CreditsCacheUtil.addCreditOper(user_id,business_type,operId);
                    break;
                case 10009://跟投
                    CombEntrustTransForm combEntrustForm =(CombEntrustTransForm)param;
                    operId = combEntrustForm.getCombi_code();
                    if(CreditsCacheUtil.isExitCreditsOper(user_id,business_type,operId)){//检查是否操作过积分
                        return;
                    }
                    CreditsCacheUtil.addCreditOper(user_id,business_type,operId);
                    break;
                case 10010://提问
                    //粉丝提问与投顾回复是同一个接口，投顾回复不需要加积分
                    AskAddForm askAddForm = (AskAddForm)param;
                    String user_type=askAddForm.getUser().getUser_type();
                    if("101".equals(user_type)){
                        return;
                    }
                    break;
                case 10011://有效的反馈
                    break;
            }
            TaskProgress taskProgress =taskProgressService.fetchByUser(user_id,business_type,company_id);
            TaskConfigure taskConfigure=null;
            if(taskProgress==null){//没有进行任何任务，查询初级任务
                taskConfigure  = taskConfigureService.findByBusinessType(business_type,company_id);
            }else{//查询当前任务的升级版任务
                TaskConfigure preTask = (TaskConfigure)taskConfigureService.get(taskProgress.getTask_id());//获取进度表中最新完成的任务
                taskConfigure = (TaskConfigure)taskConfigureService.get(preTask.getUpgrade_id());
                long finishTime = taskProgress.getUpdate_time();
//                //每个自然日零点开始计算前一天翻倍结果,判断该任务是否是昨天完成
//                if( finishTime+24*60*60000 > CreditsCacheUtil.getStartTime() && finishTime+24*60*60000 < CreditsCacheUtil.getEndTime()){
//                    multiply=preTask.getTask_award();
//                }
            }

            if(taskConfigure !=null){
                TaskProgress currentProgress = CreditsCacheUtil.getTaskProgress(user_id,company_id,taskConfigure.getTask_id());
                if(currentProgress == null){
                    currentProgress= new TaskProgress();
                    currentProgress.setTask_id(taskConfigure.getTask_id());
                    currentProgress.setCompany_id(company_id);
                    currentProgress.setUser_id(user_id);
                    currentProgress.setCompleted_count(1);
                    currentProgress.setTarget_count(taskConfigure.getTask_count());
                    currentProgress.setBusiness_type(business_type);
                    currentProgress.setCreate_time(System.currentTimeMillis());
                    currentProgress.setUpdate_time(System.currentTimeMillis());
                    if(taskConfigure.getTask_type()==1){//连续完成
                        CreditsCacheUtil.addTaskProgress(user_id,currentProgress,1);
                    }else{//某时间内完成
                        CreditsCacheUtil.addTaskProgress(user_id,currentProgress,taskConfigure.getTask_days()-1);
                    }
                }else{
                    if(currentProgress.getCompleted_count()+1 == taskConfigure.getTask_count()){//任务完成
                        currentProgress.setCompleted_count(currentProgress.getCompleted_count()+1);
                        currentProgress.setUpdate_time(System.currentTimeMillis());
                        taskProgressService.save(currentProgress);
                        CreditsCacheUtil.deleteTaskProgress(user_id,currentProgress);
                    }else {
                        currentProgress.setCompleted_count(currentProgress.getCompleted_count() + 1);
                        if(taskConfigure.getTask_type()==1) {//连续完成
                            CreditsCacheUtil.updateTaskProgress(user_id, currentProgress,1);
                        }else {
                            CreditsCacheUtil.updateTaskProgress(user_id, currentProgress);
                        }
                    }
                }
            }

            //查看昨天完成任务的奖励情况
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("user_id",user_id);
            paramMap.put("company_id",company_id);
            paramMap.put("start_time",CreditsCacheUtil.getStartTime()-24*60*60000);
            paramMap.put("end_time",CreditsCacheUtil.getEndTime()-24*60*60000);
            Integer maxMultiply = taskProgressService.findMaxMultiply(paramMap);
            if(maxMultiply !=null){
                multiply = maxMultiply;
            }

            CreditsRule creditsRule = CreditsCacheUtil.getRuleCache(company_id,business_type);
            if(creditsRule==null){
                CreditsRule creditsRuleParam = new CreditsRule();
                creditsRuleParam.setBusiness_type(business_type);
                creditsRuleParam.setCompany_id(company_id);
                creditsRule = creditsRuleService.findByBusinessType(creditsRuleParam);
                if(creditsRule==null) {
                    return ;
                }
                CreditsCacheUtil.addRuleCache(creditsRule);
            }
    //        int currentValue = CreditsCacheUtil.getUserCache(user_id,business_type,company_id);
            int currentTotalCredits = CreditsCacheUtil.getTotalCache(user_id,company_id);
            int addCredits = creditsRule.getCredits()*multiply;
            int creditsLimitValue = CreditsCacheUtil.getLimitCache(company_id);
            if(creditsLimitValue==0){
                CreditsLimit creditsLimit = creditsLimitService.findByCompany(company_id);
                if(creditsLimit !=null) {
                    CreditsCacheUtil.addLimitCache(company_id, creditsLimit.getCredits_limit_value());
                    creditsLimitValue = creditsLimit.getCredits_limit_value();
                }
            }

            if(creditsLimitValue!=0 && currentTotalCredits  > creditsLimitValue*multiply) {
                return ;
            }else if(creditsLimitValue!=0 && currentTotalCredits + addCredits > creditsLimitValue*multiply) {
                return ;
            }

            CreditsOperForm form = new CreditsOperForm();
            form.setCompany_id(company_id);
            form.setUser_id(user_id);
            form.setOpera_credits(addCredits);
            creditsService.functionAddCredits(form);

            CreditsLog creditsLog = new CreditsLog();
            creditsLog.setUser_id(user_id);
            creditsLog.setCompany_id(company_id);
            creditsLog.setOpera_credits(addCredits);
            creditsLog.setOpera_direction(1);
            creditsLog.setOpera_type(business_type);
            creditsLog.setMultiply(multiply);
            if(multiply>1){
                creditsLog.setMemo("当日任务奖励"+multiply+"倍");
            }else{
                creditsLog.setMemo("当日任务奖励未翻倍");
            }
            creditsLogService.save(creditsLog);

            CreditsCacheUtil.addUserCache(user_id,business_type,company_id,addCredits);
            CreditsCacheUtil.addTotalCache(user_id,company_id,addCredits);

        }catch (Exception e){
            LOGGER.error("积分操作错误--------",e);
            //这里要添加补偿操作
        }finally {
            return ;
        }
    }



}
